using System;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using DevExpress.XtraBars;
using System.Text;
using THSLib;
using THSERP.BusinessEntities;

namespace THSERP.BaseProvider
{
    partial class BaseModuleERP : BaseModule, IBaseModule
    {
        public uiInventoryInformation _uiInventoryInformation;
        //public uiSerieInventoryInformation _uiSerieInventoryInformation;
        //public uiOPInformation _uiOPInformation;
        //public uiHistory _uiHistory;
        public uiInformation _uiInformation;

        #region Utility Functions

        #region Include UI to Dock Panel
        protected void IncludeInformationUIToParentScreen()
        {
            ParentScreen.dockPanelSearchResults_Container.Controls.Add(_uiInformation);
            _uiInformation.Dock = DockStyle.Fill;
        }

        //protected void IncludeOPInformationUIToParentScreen()
        //{
        //    ParentScreen.dockPanelOPList_Container.Controls.Add(_uiOPInformation);
        //    _uiOPInformation.Dock = DockStyle.Fill;
        //}

        //protected void IncludeInventoryInformationUIToParentScreen()
        //{
        //    ParentScreen.dockPanelInventoryInformation_Container.Controls.Add(_uiInventoryInformation);
        //    _uiInventoryInformation.Dock = DockStyle.Fill;
        //}

        //protected void InculdeSerieInventoryInformationUIToParentScreen()
        //{
        //    ParentScreen.dockPanelSerieInventoryInformation_Container.Controls.Add(_uiSerieInventoryInformation);
        //    _uiSerieInventoryInformation.Dock = DockStyle.Fill;
        //}

        //protected void IncludeHistoryUIToParentScreen()
        //{
        //    ParentScreen.dockPanelHistory_Container.Controls.Add(_uiHistory);
        //    _uiHistory.Dock = DockStyle.Fill;
        //}
        #endregion
#if never
       


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="ContactTypeControlName" type="String"></THSparam>
        public void ShowContactTypeScreen(object sender, String strEventName)
        {
            String strContactTypeControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                sender, strEventName,
                                                "ShowContactTypeScreen",
                                                "ContactTypeControlName");
            MAContactsInfo objMAContactsInfo = (MAContactsInfo)CurrentModuleEntity.ModuleObjects["MAContacts"];
            if (objMAContactsInfo != null)
            {
                guiContactType _guiContactType = new guiContactType(strContactTypeControlName);
                _guiContactType.Module = this;
                _guiContactType.ShowDialog();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="DiscountPercentControlName" type="String"></THSparam>
        /// <THSparam name="DiscountFixControlName" type="String"></THSparam>
        public void SetVisibleOfDiscountControls(object sender, String strEventName)
        {
            String strDiscountPercentControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                    sender, strEventName,
                                                    "SetVisibleOfDiscountControls",
                                                    "DiscountPercentControlName");
            String strDiscountFixControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                sender, strEventName,
                                                "SetVisibleOfDiscountControls",
                                                "DiscountFixControlName");
            bool bIsDiscountPercent = (sender as DevExpress.XtraEditors.CheckEdit).Checked;

            if (Controls[strDiscountFixControlName] != null && Controls[strDiscountPercentControlName] != null)
            {
                if (bIsDiscountPercent)
                {
                    Controls[strDiscountPercentControlName].Enabled = true;
                    Controls[strDiscountFixControlName].Enabled = false;
                }
                else
                {
                    Controls[strDiscountPercentControlName].Enabled = false;
                    Controls[strDiscountFixControlName].Enabled = true;
                }
            }
        }

        public virtual void SetReadonlyProductQtyControl()
        {
            
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(CurrentModuleEntity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            String strModuleItemProductQtyPropertyName = strModuleItemsObjectName.Substring(0, strModuleItemsObjectName.Length - 1) + "ProductQty";

            STFieldsInfo objProductQtyFieldsInfo = new STFieldsController().GetFirstFieldByModuleIDAndUserGroupIDAndFieldDataSourceAndFieldDataMember(
                                                                            ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                            strModuleItemsObjectName, strModuleItemProductQtyPropertyName);
            if (objProductQtyFieldsInfo != null)
            {

                int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(CurrentModuleEntity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));
                MAProductsController objMAProductsController = new MAProductsController();
                if (objMAProductsController.ProductHaveSerieNumber(iMAProductID))
                {
                    ((DevExpress.XtraEditors.TextEdit)Controls[objProductQtyFieldsInfo.STFieldName]).Properties.ReadOnly = true;
                }
                else
                {
                    ((DevExpress.XtraEditors.TextEdit)Controls[objProductQtyFieldsInfo.STFieldName]).Properties.ReadOnly = false;
                }
            }
        }        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        public virtual void ShowSerieNumbersScreen(object sender, String strEventName)
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));

            if (iMAProductID > 0)
            {
                MAProductsController objMAProductsController = new MAProductsController();
                MAProductsInfo objMAProductsInfo = (MAProductsInfo)objMAProductsController.GetObjectByID(iMAProductID);
                if (objMAProductsInfo != null)
                {
                    if (objMAProductsInfo.MAProductType.Contains("Category"))
                    {
                        guiSubProducts _guiSubProducts = new guiSubProducts(this);
                        _guiSubProducts.ShowDialog();
                    }
                    else
                    {
                        if (this.Name == "Shipment")
                        {
                            if (((FAShipmentsInfo)entity.MainObject).FAShipmentTypeCombo == ADConfigValueUtility.cstShipmentTypeFromSellOrder)
                            {
                                if (objMAProductsController.ProductHaveSerieNumber(iMAProductID))
                                {
                                    guiShipmentSerieNumber _guiShipmentSerieNumber = new guiShipmentSerieNumber(this);
                                    _guiShipmentSerieNumber.ShowDialog();
                                }
                            }
                            else
                            {
                                //if product have serial number,focus Serie Number Grid
                                if (objMAProductsController.ProductHaveSerieNumber(iMAProductID))
                                {
                                    guiSerieNumber _guiSerieNumber = new guiSerieNumber(this);
                                    _guiSerieNumber.ShowDialog();
                                }
                            }
                        }
                        else
                        {
                            //if product have serial number,focus Serie Number Grid
                            if (objMAProductsController.ProductHaveSerieNumber(iMAProductID))
                            {
                                guiSerieNumber _guiSerieNumber = new guiSerieNumber(this);
                                _guiSerieNumber.ShowDialog();
                            }
                        }
                    }
                }
            }
        }

        public void InvalidateSerieNumberGridControl()
        {
            _uiInformation.InitSerieNumbersGridControl();
        }

        public void InvalidateOPInformation()
        {
            _uiOPInformation.InvalidateOPInformation();
        }


        public void SetEnablesOfNotEditControls(bool bIsEnable)
        {
            STFieldsController objSTFieldsController = new STFieldsController();
            DataSet dsFields = objSTFieldsController.GetFieldByModuleIDAndUserGroupIDAndFieldGroup(
                                                        ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                        "NotEdit");
            if (dsFields.Tables.Count > 0)
            {
                foreach (DataRow rowField in dsFields.Tables[0].Rows)
                {
                    STFieldsInfo objSTFieldsInfo = (STFieldsInfo)objSTFieldsController.GetObjectFromDataRow(rowField);
                    if (objSTFieldsInfo != null)
                    {
                        if (Controls[objSTFieldsInfo.STFieldName] != null)
                        {
                            Controls[objSTFieldsInfo.STFieldName].Enabled = bIsEnable;
                        }
                    }
                }
            }
        }

        public void SetEnableOfItemActionControls(bool bIsEnable)
        {
            STFieldsController objSTFieldsController = new STFieldsController();
            DataSet dsFields = objSTFieldsController.GetFieldByModuleIDAndUserGroupIDAndFieldGroup(
                                                        ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                        "ItemAction");
            if (dsFields.Tables.Count > 0)
            {
                foreach (DataRow rowField in dsFields.Tables[0].Rows)
                {
                    STFieldsInfo objSTFieldsInfo = (STFieldsInfo)objSTFieldsController.GetObjectFromDataRow(rowField);
                    if (objSTFieldsInfo != null)
                    {
                        if (Controls[objSTFieldsInfo.STFieldName] != null)
                        {
                            Controls[objSTFieldsInfo.STFieldName].Enabled = bIsEnable;
                        }
                    }
                }
            }
        }

#endif
        #region Set Default Values From Customer,Supplier
        public virtual void SetDefaultValuesFromCustomer()
        {
            CurrentModuleEntity.SetDefaultValuesFromCustomer();
        }

        // changes, 08/05/2008
        public virtual void SetDefaultValuesFromSupplier()
        {
            CurrentModuleEntity.SetDefaultValuesFromSupplier();
        }
        #endregion

#if never
        #region Set Default Values From Product

        public virtual void SetProductDescription()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            String strModuleItemProductDescPropertyName = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductDesc";
            int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));

            MAProductsInfo objMAProductsInfo = (MAProductsInfo)new MAProductsController().GetObjectByID(iMAProductID);
            if (objMAProductsInfo != null)
            {
                THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductDescPropertyName, objMAProductsInfo.MAProductDesc);
                entity.UpdateModuleObjectBindingSource(strModuleItemsObjectName);
            }
        }


        public virtual void SetProductPrice()
        {
            CurrentModuleEntity.SetProductPrice();
        }

        public virtual void GetOriginalProductPrice()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            String strSellPriceCombo = String.Empty;
            String strProductPriceDesc = String.Empty;

            int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));
            if (iMAProductID > 0)
            {

                String strSellPrice = THSDbUtil.GetPropertyValue(entity.MainObject, "FASellPriceCombo").ToString();
                if (strSellPrice.Length > (ADConfigValueUtility.ADConfigValueSellPrice.Length + 1))
                {
                    strSellPriceCombo = strSellPrice.Substring(ADConfigValueUtility.ADConfigValueSellPrice.Length);
                }
                else
                {
                    strSellPriceCombo = "01";
                }
                MAProductsInfo objMAProductsInfo = (MAProductsInfo)new MAProductsController().GetObjectByID(iMAProductID);

                String strCurrency = string.Empty;
                STFieldsInfo objSTFieldsInfoCurrency =
                    new STFieldsController().GetFieldByModuleIDAndUserGroupIDAndFieldDataSourceAndFieldTypeAndFieldTagAndLikeFieldDataMember(
                                                                            ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                            strMainObjectName, "THSLookupEdit", "DC", "fld_lkeFACurrencyIDCombo");
                if (objSTFieldsInfoCurrency != null)
                {
                    strCurrency = Controls[objSTFieldsInfoCurrency.STFieldName].Text;
                }

                double dbProductPrice = 0.0;
                if (objMAProductsInfo != null)
                {
                    String strPriceLevel = ADConfigValueUtility.GetTextFromKey(strSellPrice);
                    dbProductPrice = Convert.ToDouble(THSDbUtil.GetPropertyValue(objMAProductsInfo, "MAProductPrice" + strSellPriceCombo));
                    strProductPriceDesc = String.Format("{0} {1} - {2}", dbProductPrice, strCurrency, strPriceLevel);
                }
                STFieldsInfo objSTFieldsInfo =
                    new STFieldsController().GetFirstFieldByModuleIDAndUserGroupIDAndFieldDataSourceAndFieldTypeAndFieldTag(
                                                                            ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                            strModuleItemsObjectName, "THSLabel", "Price");
                if (objSTFieldsInfo != null)
                {
                    Controls[objSTFieldsInfo.STFieldName].Text = strProductPriceDesc;
                }
                //STFieldsInfo objSTFieldsInfoPrice = 
                //    new STFieldsController().GetFieldByModuleIDAndUserGroupIDAndFieldDataSourceAndFieldTypeAndFieldTagAndLikeFieldDataMember(
                //                                                            ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                //                                                            strModuleItemsObjectName, "THSTextBox", "DC","ItemProductUnitPrice");
                //if (objSTFieldsInfoPrice != null)
                //{
                //    Controls[objSTFieldsInfoPrice.STFieldName].Text = dbProductPrice.ToString();
                //}
            }
        }

        public virtual void SetProductPriceByProductUnitPrice()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";

            String strModuleItemProductUnitPricePropertyName = strModuleItemsObjectName.Substring(0, strModuleItemsObjectName.Length - 1) + "ProductUnitPrice";
            String strModuleItemProductQtyPropertyName = strModuleItemsObjectName.Substring(0, strModuleItemsObjectName.Length - 1) + "ProductQty";
            String strModuleItemPricePropertyName = strModuleItemsObjectName.Substring(0, strModuleItemsObjectName.Length - 1) + "Price";


            double dbProductUnitPrice = Convert.ToDouble(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductUnitPricePropertyName));
            double dbProductQty = Convert.ToDouble(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductQtyPropertyName));

            THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemPricePropertyName, dbProductUnitPrice * dbProductQty);
            entity.UpdateModuleObjectBindingSource(strModuleItemsObjectName);
        }

        public virtual double SetProductDiscount(MAProductsInfo objMAProductsInfo)
        {
            double dbProductDiscount = 0;
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";

            int iMACustomerID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.MainObject, "FACustomerIDCombo"));
            if (iMACustomerID > 0)
            {
                int iMAProductGroupID = objMAProductsInfo.MAProductGroupIDCombo;
                if (iMAProductGroupID > 0)
                {
                    MACustomerProductGroupDiscountController objMACustomerProductGroupDiscountController = new MACustomerProductGroupDiscountController();
                    MACustomerProductGroupDiscountsInfo objMACustomerProductGroupDiscountInfo = objMACustomerProductGroupDiscountController.GetMACustomerProductGroupDiscountByMACustomerIDAndMAProductGroupID(
                                                                                                                                            iMACustomerID, iMAProductGroupID);
                    if (objMACustomerProductGroupDiscountInfo != null)
                    {
                        dbProductDiscount = objMACustomerProductGroupDiscountInfo.MACustomerProductGroupDiscountPercent;
                    }
                }
            }
            return dbProductDiscount;

        }

        public virtual double SetDefaultProductTaxPercent(MAProductsInfo objMAProductsInfo)
        {
            double dbTaxPercent = 0;

            int iGEVATID = objMAProductsInfo.MAVATIDCombo;
            if (iGEVATID > 0)
            {
                GEVATsController objGEVATsController = new GEVATsController();
                GEVATsInfo objGEVATsInfo = (GEVATsInfo)objGEVATsController.GetObjectByID(iGEVATID);
                if (objGEVATsInfo != null)
                {
                    dbTaxPercent = objGEVATsInfo.GEVATPercentValue;

                }
            }
            return dbTaxPercent;

        }

        public virtual void SetDefaultStockAndStockSlot()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));

            MAProductsInfo objMAProductsInfo = (MAProductsInfo)new MAProductsController().GetObjectByID(iMAProductID);
            if (objMAProductsInfo != null)
            {
                THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAStockIDCombo", objMAProductsInfo.MAStockIDCombo);
                THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAStockSlotIDCombo", objMAProductsInfo.MAStockSlotIDCombo);
                entity.UpdateModuleObjectBindingSource(strModuleItemsObjectName);
            }
        }

        public virtual void SetBasicAndPackageQty()
        {
            try
            {
                
                ERPModuleEntities entity = this.CurrentModuleEntity;
                String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
                String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
                String strModuleItemProductQtyPropertyName = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductQty";
                String strModuleItemProductSellFactorPropertyName = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductSellFactor";
                String strModuleItemProductPackagingFactorPropertyName = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductPackagingFactor";
                String strModuleItemProductBasicQtyPropertyName = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductBasicQty";
                String strModuleItemProductPackagingQtyPropertyname = strMainObjectName.Substring(0, 2) + this.Name + "ItemProductPakagingQty";

                int iMAProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FAProductIDCombo"));

                double dbItemSellQty = Convert.ToDouble(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductQtyPropertyName));
                double dbSellFactor = Convert.ToDouble(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductSellFactorPropertyName));
                double dbItemPackagingFactor = Convert.ToDouble(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductPackagingFactorPropertyName));

                if (dbSellFactor > 0)
                {
                    double dbItemBasicQty = dbItemSellQty / dbSellFactor;
                    double dbItemPackagingQty = 0;
                    if (dbItemPackagingFactor > 0)
                        dbItemPackagingQty = dbItemBasicQty / dbItemPackagingFactor;

                    THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductBasicQtyPropertyName, dbItemBasicQty);
                    THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductPackagingQtyPropertyname, dbItemPackagingQty);
                }
                else
                {
                    THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductBasicQtyPropertyName, 0);
                    THSDbUtil.SetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemProductPackagingQtyPropertyname, 0);
                }

            }
            catch (Exception)
            {
                return;
            }
        }
        #endregion
#endif
        #endregion

        #region Calculate Product Quantity on Stock
        public virtual void CalculateTotalProductQuantityForAllStock()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            int iICProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FK_ICProductID"));


            ICInventoryStocksController objICInventoryStocksController = new ICInventoryStocksController();

            double dbTotalStockQuantity = 0;
            double dbTotaProposalStockQuantity = 0;
            double dbTotalSaleOrderStockQuantity = 0;
            double dbTotalPurchaseOrderStockQuantity = 0;

            if (iICProductID > 0)
            {
                dbTotalStockQuantity = objICInventoryStocksController.GetTotalStockQuantityByProduct(iICProductID);
                dbTotaProposalStockQuantity = objICInventoryStocksController.GetTotalStockProposalQuantityByProduct(iICProductID);
                dbTotalSaleOrderStockQuantity = objICInventoryStocksController.GetTotalStockSaleOrderQuantityByProduct(iICProductID);
                dbTotalPurchaseOrderStockQuantity = objICInventoryStocksController.GetTotalStockPurchaseOrderQuantityByProduct(iICProductID);
            }

            _uiInventoryInformation.ShowTotalProductQuantityForAllStock(dbTotalStockQuantity,
                                                                        dbTotaProposalStockQuantity,
                                                                        dbTotalSaleOrderStockQuantity,
                                                                        dbTotalPurchaseOrderStockQuantity);
        }

        public virtual void CalculateProductQuantityForProductStock()
        {
            
            ERPModuleEntities entity = this.CurrentModuleEntity;
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + this.Name + "Items";
            int iICProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FK_ICProductID"));

            int iICStockID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], "FK_ICStockID"));

            ICInventoryStocksController objICInventoryStocksController = new ICInventoryStocksController();


            double dbStockQuantity = 0;
            double dbProposalStockQuantity = 0;
            double dbSaleOrderStockQuantity = 0;
            double dbPurchaseOrderStockQuantity = 0;
            String strICStockName = String.Empty;

            if (iICProductID > 0 && iICStockID > 0)
            {
                dbStockQuantity = objICInventoryStocksController.GetStockQuantityByProductAndStock(iICProductID, iICStockID);
                dbProposalStockQuantity = objICInventoryStocksController.GetStockProposalQuantityByProductAndStock(iICProductID, iICStockID);
                dbSaleOrderStockQuantity = objICInventoryStocksController.GetStockSaleOrderQuantityByProductAndStock(iICProductID, iICStockID);
                dbPurchaseOrderStockQuantity = objICInventoryStocksController.GetStockPurchaseOrderQuantityByProductAndStock(iICProductID, iICStockID);
                strICStockName = new ICStocksController().GetObjectNameByID(iICStockID);
            }

            _uiInventoryInformation.ShowProductQuantityForProductStock(dbStockQuantity,
                                                                       dbProposalStockQuantity,
                                                                       dbSaleOrderStockQuantity,
                                                                       dbPurchaseOrderStockQuantity,
                                                                       strICStockName);

        }


        public virtual void CalculateTotalProductQuantityForAllStock(int iICProductID)
        {

            ICInventoryStocksController objICInventoryStocksController = new ICInventoryStocksController();

            double dbTotalStockQuantity = 0;
            double dbTotaProposalStockQuantity = 0;
            double dbTotalSaleOrderStockQuantity = 0;
            double dbTotalPurchaseOrderStockQuantity = 0;

            if (iICProductID > 0)
            {
                dbTotalStockQuantity = objICInventoryStocksController.GetTotalStockQuantityByProduct(iICProductID);
                dbTotaProposalStockQuantity = objICInventoryStocksController.GetTotalStockProposalQuantityByProduct(iICProductID);
                dbTotalSaleOrderStockQuantity = objICInventoryStocksController.GetTotalStockSaleOrderQuantityByProduct(iICProductID);
                dbTotalPurchaseOrderStockQuantity = objICInventoryStocksController.GetTotalStockPurchaseOrderQuantityByProduct(iICProductID);
            }

            _uiInventoryInformation.ShowTotalProductQuantityForAllStock(dbTotalStockQuantity,
                                                                        dbTotaProposalStockQuantity,
                                                                        dbTotalSaleOrderStockQuantity,
                                                                        dbTotalPurchaseOrderStockQuantity);
        }

        public virtual void CalculateProductQuantityForProductStock(int iICProductID, int iICStockID)
        {
            ICInventoryStocksController objICInventoryStocksController = new ICInventoryStocksController();
            STFieldsController objSTFieldsController = new STFieldsController();

            double dbStockQuantity = 0;
            double dbProposalStockQuantity = 0;
            double dbSaleOrderStockQuantity = 0;
            double dbPurchaseOrderStockQuantity = 0;
            String strICStockName = String.Empty;

            if (iICProductID > 0 && iICStockID > 0)
            {
                dbStockQuantity = objICInventoryStocksController.GetStockQuantityByProductAndStock(iICProductID, iICStockID);
                dbProposalStockQuantity = objICInventoryStocksController.GetStockProposalQuantityByProductAndStock(iICProductID, iICStockID);
                dbSaleOrderStockQuantity = objICInventoryStocksController.GetStockSaleOrderQuantityByProductAndStock(iICProductID, iICStockID);
                dbPurchaseOrderStockQuantity = objICInventoryStocksController.GetStockPurchaseOrderQuantityByProductAndStock(iICProductID, iICStockID);
                strICStockName = new ICStocksController().GetObjectNameByID(iICStockID);
            }

            _uiInventoryInformation.ShowProductQuantityForProductStock(dbStockQuantity,
                                                                       dbProposalStockQuantity,
                                                                       dbSaleOrderStockQuantity,
                                                                       dbPurchaseOrderStockQuantity,
                                                                       strICStockName);

        }
        #endregion

        #region Generate Search Query, add 14.05.2008, Generate Search Query based on Search Fields of Module

        public virtual String GenerateSearchQuery(String strTableName)
        {
            StringBuilder strSearchQueryBuilder = new StringBuilder();
            strSearchQueryBuilder.Append(GenerateSearchQueryHeader(strTableName));
            strSearchQueryBuilder.Append("WHERE" + THSUtil.NewLine);
            strSearchQueryBuilder.Append(GenerateConditionsForSearch(strTableName));
            strSearchQueryBuilder.Append(THSUtil.NewLine);
            return strSearchQueryBuilder.ToString();
        }
        public String MergeSearchQueryWithPlusQuery(String origianlQuery, String plusQuery)
        {
            int index = origianlQuery.IndexOf("ORDER BY");
            return origianlQuery.Insert(index, plusQuery);
        }
        public virtual String GenerateSearchQueryHeader(String strTableName)
        {
            StringBuilder strSearchQueryHeaderBuilder = new StringBuilder();
            if (Controls[THSApp.cstTopResultsSearchControl] != null)
            {
                int iTopResults = Convert.ToInt32(((DevExpress.XtraEditors.BaseEdit)Controls[THSApp.cstTopResultsSearchControl]).EditValue);
                //iTopResults must be greater or equal 0__25/03/2010
                if (iTopResults < 0)
                    iTopResults = 0;
                strSearchQueryHeaderBuilder.Append(String.Format("SELECT TOP({0}) ", iTopResults));
                strSearchQueryHeaderBuilder.Append("* FROM [dbo]." + strTableName + THSUtil.NewLine);
            }
            else
            {
                strSearchQueryHeaderBuilder.Append("SELECT * FROM [dbo]." + strTableName + THSUtil.NewLine);
            }

            return strSearchQueryHeaderBuilder.ToString();
        }

        public virtual String GenerateConditionsForSearch(String strTableName)
        {
            
            StringBuilder strConditionBuilder = new StringBuilder();
            STFieldsController objSTFieldsController = new STFieldsController();
            //Remove panel search option on ParentScreen HieuNH_22/05/2010
            //foreach (Control ctrl in ParentScreen.fld_pnlSearchOption.Controls)
            foreach (Control ctrl in SearchScreen.CriteriaSection.Controls)
                if (ctrl.Tag != null && ctrl.Tag.ToString() == THSERPScreen.SearchControl)
                {
                    String strColumnName = THSDbUtil.GetPropertyStringValue(ctrl, THSERPScreen.cstDataMemberPropertyName);
                    strConditionBuilder.Append(GenerateConditionsForSearch(ctrl, strTableName, strColumnName));
                }
            strConditionBuilder.Append(THSUtil.Tab + String.Format("([AAStatus]='Alive')") + THSUtil.NewLine);
            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strTableName);
            strConditionBuilder.Append(THSUtil.Tab + String.Format("ORDER BY [{0}] DESC ", strPrimaryColumn));
            return strConditionBuilder.ToString();
        }

        public virtual String GenerateConditionsForSearch(Control ctrl, String strTableName, String strColumnName)
        {
            
            StringBuilder strConditionBuilder = new StringBuilder();
            String strFieldName = ctrl.Name;
            if (strFieldName.Contains("TopResult"))
                return String.Empty;
            String strColumnDbType = THSDbUtil.GetColumnDbType(strTableName, strColumnName);
            if (((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue == null)
                return String.Empty;
            if (((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue.ToString() == String.Empty)
                return String.Empty;

            if (!THSDbUtil.IsForeignKey(strTableName, strColumnName))
            {
                if (strColumnDbType.Contains("varchar") || strColumnDbType.Contains("nvarchar"))
                {
                    #region varchar
                    String strColumnValue = ((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue.ToString();
                    if (strFieldName.Contains("SearchFrom"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] >= '{1}' +'%'))",
                                strColumnName, strColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] >= '{1}' +'%')", strColumnName, strColumnValue));
                    }
                    else if (strFieldName.Contains("SearchTo"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] <= '{1}' +'%'))",
                                strColumnName, strColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] <= '{1}' +'%')", strColumnName, strColumnValue));
                    }
                    else
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] LIKE N'{1}' +'%'))", strColumnName, strColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] LIKE N'{1}' +'%')", strColumnName, strColumnValue));
                    }

                    strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
                    #endregion

                }
                else if (strColumnDbType.Contains("datetime"))
                {
                    //hieu nguyen remove,March 14,2010
#if never 
                            //DateTime dtColumnValue = Convert.ToDateTime(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue);

                            //if (strFieldName.Contains("SearchFrom"))
                            //{
                            //    if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] >= '{1}'))",
                            //            strColumnName, dtColumnValue));
                            //    else
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] >= '{1}')",
                            //            strColumnName, dtColumnValue));
                            //}
                            //else if (strFieldName.Contains("SearchTo"))
                            //{
                            //    dtColumnValue=dtColumnValue.AddDays(1.0);
                            //    if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] <= '{1}'))",
                            //            strColumnName, dtColumnValue));
                            //    else
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] <= '{1}')",
                            //            strColumnName, dtColumnValue));
                            //}
                            //else
                            //{
                            //    if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] = '{1}'))",
                            //            strColumnName, dtColumnValue));
                            //    else
                            //        strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] = '{1}')",
                            //            strColumnName, dtColumnValue));
                            //}
#endif
                    //hieu nguyen Add search datetime value and fix bug search DateTime.MaxValue

                    #region datetime
                    DateTime dtColumnValue = Convert.ToDateTime(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue);
                    String strFormatDatetime = String.Format("yyyyMMdd");
                    if (strFieldName.Contains("SearchFrom"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR (CONVERT(VARCHAR(10), [{0}], 112) >= CONVERT(VARCHAR(10),'{1}', 112)))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("((CONVERT(VARCHAR(10), [{0}], 112) >= CONVERT(VARCHAR(10),'{1}', 112)))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                    }
                    else if (strFieldName.Contains("SearchTo"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR(CONVERT(VARCHAR(10), [{0}], 112) <= CONVERT(VARCHAR(10),'{1}', 112)))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("((CONVERT(VARCHAR(10), [{0}], 112) <= CONVERT(VARCHAR(10),'{1}', 112)))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                    }
                    else
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR(CONVERT(VARCHAR(10), [{0}], 112) = CONVERT(VARCHAR(10),'{1}', 112)))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("((CONVERT(VARCHAR(10), [{0}], 112) = CONVERT(VARCHAR(20),'{1}', 112))",
                                strColumnName, dtColumnValue.ToString(strFormatDatetime)));
                    }

                    strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
                    #endregion
                }

                else if (strColumnDbType.Contains("int"))
                {
                    #region int
                    int iColumnValue = Convert.ToInt32(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue.ToString());

                    if (strFieldName.Contains("SearchFrom"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] >= {1}))",
                                strColumnName, iColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] >= {1})", strColumnName, iColumnValue));
                    }
                    else if (strFieldName.Contains("SearchTo"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] <= {1}))",
                                strColumnName, iColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] <= {1})", strColumnName, iColumnValue));
                    }
                    else
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] = {1}))", strColumnName, iColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] = {1})", strColumnName, iColumnValue));
                    }

                    strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
                    #endregion
                }
                else if (strColumnDbType.Contains("float"))
                {
                    #region float
                    double dbColumnValue = Convert.ToDouble(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue.ToString());
                    if (strFieldName.Contains("SearchFrom"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] >= {1}))",
                                strColumnName, dbColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] >= {1})", strColumnName, dbColumnValue));
                    }
                    else if (strFieldName.Contains("SearchTo"))
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] <= {1}))",
                                strColumnName, dbColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] <= {1})", strColumnName, dbColumnValue));
                    }
                    else
                    {
                        if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] = {1}))", strColumnName, dbColumnValue));
                        else
                            strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] = {1})", strColumnName, dbColumnValue));
                    }

                    strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
                    #endregion
                }
                else if (strColumnDbType.Contains("bit"))
                {
                    #region Bit
                    bool bColumnValue = Convert.ToBoolean(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue);
                    if (THSDbUtil.ColumnIsAllowNull(strTableName, strColumnName))
                        strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] IS NULL)OR([{0}] = {1}))", strColumnName, bColumnValue));
                    else
                        strConditionBuilder.Append(THSUtil.Tab + String.Format("([{0}] = {1})", strColumnName, bColumnValue));

                    strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
                    #endregion
                }
                else
                {
                    //Comment this row, ignore if column name is unknown__24/03/2010
                    //MessageBox.Show(String.Format("Bug: unknown Type <{0}> <{1}>", "Bug", strColumnName, strColumnDbType));
                    return String.Empty;
                }
            }
            else
            {
                int iColumnValue = Convert.ToInt32(((DevExpress.XtraEditors.BaseEdit)ctrl).EditValue);
                strConditionBuilder.Append(THSUtil.Tab + String.Format("(([{0}] ={1})OR({1} =0))", strColumnName, iColumnValue));
                strConditionBuilder.Append(THSUtil.NewLine + THSUtil.Tab + "AND" + THSUtil.NewLine);
            }
            return strConditionBuilder.ToString();
        }
        #endregion

        // adds, 17/10/2008
        public virtual void DisplayLabelText(BusinessObject obj, Control ctrl)
        {
            if (ctrl.GetType() == typeof(THSLabel) || ctrl.GetType() == typeof(Label) || ctrl.GetType() == typeof(DevExpress.XtraEditors.LabelControl))
            {
                String strObjectTableName = THSUtil.GetTableNameFromBusinessObject(obj);
                String strDataSource = String.Empty;
                String strDataMember = String.Empty;
                if (!String.IsNullOrEmpty(ctrl.AccessibleName))
                {
                    strDataSource = ctrl.AccessibleName.Split(';')[0];
                    strDataMember = ctrl.AccessibleName.Split(';')[1];
                }
                int iFieldFormatGroupID = 0;
                if (!String.IsNullOrEmpty(ctrl.AccessibleDescription))
                    iFieldFormatGroupID = Convert.ToInt32(ctrl.AccessibleDescription.Split(';')[2]);
                if (!String.IsNullOrEmpty(strDataSource) && !String.IsNullOrEmpty(strDataMember))
                {
                    if (strDataSource == strObjectTableName)
                    {
                        PropertyInfo prop = obj.GetType().GetProperty(strDataMember);
                        if (prop != null)
                        {
                            object objValue = prop.GetValue(obj, null);
                            //Type columnType = THSUtil.GetColumnDataType(strDataSource, strDataMember);
                            Type columnType = objValue.GetType();
                            if (columnType == typeof(String))
                                ctrl.Text = objValue.ToString();
                            else if (columnType == typeof(int))
                                ctrl.Text = THSUtil.GetNumberDisplayFormat(Convert.ToInt32(objValue));
                            else if (columnType == typeof(double))
                            {
                                double dblValue = Convert.ToDouble(objValue);
                                STFieldFormatGroupsInfo objFieldFormatGroupsInfo = (STFieldFormatGroupsInfo)THSApp.FieldFormatGroups[iFieldFormatGroupID];
                                if (objFieldFormatGroupsInfo != null)
                                {
                                    if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                                        dblValue = Math.Round(dblValue, objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound, MidpointRounding.AwayFromZero);
                                }
                                ctrl.Text = THSUtil.GetNumberDisplayFormat(dblValue);
                            }
                            else if (columnType == typeof(decimal))
                            {
                                decimal decValue = Convert.ToDecimal(objValue);
                                STFieldFormatGroupsInfo objFieldFormatGroupsInfo = (STFieldFormatGroupsInfo)THSApp.FieldFormatGroups[iFieldFormatGroupID];
                                if (objFieldFormatGroupsInfo != null)
                                {
                                    if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                                        decValue = Math.Round(decValue, objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound, MidpointRounding.AwayFromZero);
                                }
                                ctrl.Text = THSUtil.GetNumberDisplayFormat(decValue);
                            }
                            else if (columnType == typeof(DateTime))
                            {
                                DateTime dtValue =Convert.ToDateTime(objValue);
                                if (ctrl.Tag != null)
                                {
                                    if (ctrl.Tag.ToString().Equals("Time"))
                                        ctrl.Text = dtValue.ToString("HH:mm:ss");
                                    else if(ctrl.Tag.ToString().Equals("Date"))
                                        ctrl.Text = dtValue.ToString("dd/MM/yyyy");
                                    else
                                        ctrl.Text = dtValue.ToString("dd/MM/yyyy");
                                }
                                else
                                    ctrl.Text =dtValue.ToString("dd/MM/yyyy");

                            }
                            else if (columnType == typeof(bool))
                                ctrl.Text = objValue.ToString();
                            else
                                ctrl.Text = objValue.ToString();
                        }
                    }
                }
            }
        }

        public virtual void DisplayLabelText(BusinessObject obj)
        {
            foreach (DictionaryEntry entry in Controls)
            {
                Control ctrl = (Control)entry.Value;
                DisplayLabelText(obj, ctrl);
            }
        }

        public virtual bool HasPrivilege(String privilegeName)
        {
            if (!String.IsNullOrEmpty(privilegeName))
            {
                ADPrivilegesController objPrivilegesController = new ADPrivilegesController();
                ADPrivilegesInfo objPrivilegesInfo = objPrivilegesController.GetPrivilegeByNameAndModuleID(privilegeName, ModuleID);
                if (objPrivilegesInfo == null)
                    return true;
                ADPrivilegeUserGroupsController objPrivilegeUserGroupsController = new ADPrivilegeUserGroupsController();
                ADPrivilegeUserGroupsInfo objPrivilegeUserGroupsInfo = objPrivilegeUserGroupsController.GetObjectByPrivilegeIDAndUserGroupID(objPrivilegesInfo.ADPrivilegeID, THSApp.CurrentUserGroupInfo.ADUserGroupID);

                if (objPrivilegeUserGroupsInfo == null || objPrivilegeUserGroupsInfo.ADPrivilegeUserGroupCheck == false)
                    return false;
            }
            return true;
        }
    }
}
